package org.zhtkj.jt808.codec;

import org.zhtkj.framework.codec.MessageDecoder;
import org.zhtkj.framework.message.Header;
import org.zhtkj.framework.message.PackageData;
import org.zhtkj.web.jt808.dto.RegisterResult;
import org.zhtkj.web.utils.JT808ProtocolUtils;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.ReferenceCountUtil;

public class ClientHandle extends SimpleChannelInboundHandler<ByteBuf>{

	private MessageDecoder decoder;
	public String replyToken;
	
	public ClientHandle(MessageDecoder decoder) {
		this.decoder = decoder;
	}
	
	 @Override
	 public void channelActive(ChannelHandlerContext ctx) throws Exception {
		 System.out.println("client channelActive..");
	 }
	 
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
		if(msg.readableBytes() <=0 )
			return;
		
        String hex = ByteBufUtil.hexDump(msg);
        System.out.println(hex);
        
		msg = JT808ProtocolUtils.doEscape4Receive(msg);
		Header header = decoder.decodeHeader(msg);
		ByteBuf bodyBuf = msg.slice(header.getHeaderLength(), header.getBodyLength());
		
		if(header.getType() == 0x8100) {
			PackageData<?> body = decoder.decodeBody(bodyBuf, RegisterResult.class);
			replyToken = ((RegisterResult)body).getReplyToken();
			//System.out.println(replyToken);
		}else{

		}
		//ReferenceCountUtil.release(msg);
	}
	
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }	

}
